package com.shruijin.wy.thread.pool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ThreadPool {

    private final static int TOTAL_COUNT = 100;


    public void shutdown()  {
        ExecutorService executor = Executors.newCachedThreadPool();
        final CountDownLatch countDownLatch = new CountDownLatch(TOTAL_COUNT);

        for (int i=0;i<TOTAL_COUNT;i++){
            final int threadId = i+1;
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        printMsg(threadId);
                        countDownLatch.countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        try{
            countDownLatch.await();
            //优雅销毁线程池
            executor.shutdown();
            while (!executor.awaitTermination(1, TimeUnit.SECONDS)){
                log.info("线程池状态：待结束");
            }
            log.info("线程池销毁！");
        } catch (Exception exp){
            log.error(exp.getMessage());
        }

    }

    private void printMsg(int threadId) throws InterruptedException {
        log.info("/n thread :"+threadId+" is running!");
        Thread.sleep(1000);
        log.info("/n thread :"+threadId+" is shutdown!!!");
    }

}
